""" 

    Transparency.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
        
    This page displays the information about how digitally transparent your legislators are
    and asks you to support digital transparency.
    
"""

__author__ = "Will Turnage (will@wubbahed.com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string

from sets import Set
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.ext import db
from utils import fbUtil, dbUtil, UserDistrict, SunlightUtil

class MainHandler(webapp.RequestHandler):
        
    def post(self):
    
        try:
            #check if Facebook app is installed
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, True, "transparency")
            if self.facebookapi is None:
                return
                   
            user = self.facebookapi.users.getInfo([self.facebookapi.uid], ['uid', 'name', 'current_location'])[0]
            userInfo = dbUtil().getLegislatorForUser(user["uid"], user["current_location"], True)
            if userInfo is None:
                self.response.out.write('<fb:redirect url="/representedby/location" />')
            else:  
                
                legislator_keys = ["rep", "jrsen", "srsen"]          
                userInfo["section"] = "transparency"
            
                path = os.path.join(os.path.dirname(__file__), '../templates/heading.fbml')
                self.response.out.write(template.render(path, userInfo))

                legislators = {"legislators":[], "digitalindex":[[]], "flags": {"official_rss": [], "twitter_id": [], "youtube_url": []}, "loggedin": True, "discussion_board": {"id": "", "name": "your legislators", "modifier": "with"}}
                digital_keys = {"email": "Email Address", "official_rss": "RSS feed", "twitter_id": "Twitter account", "youtube_url": "YouTube account"}
                digital_key = ["email", "official_rss", "twitter_id", "youtube_url"]
                for key in digital_key:
                    legislators["digitalindex"].append([digital_keys[key]])                            
                legislators["digitalindex"].append(["Digital Transparency Index"]) 
                sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
        
                if userInfo is not None:
                    for title in legislator_keys:
                        if userInfo.has_key(title):
                            if userInfo[title] is not None:
                                if userInfo[title] != "BLANK":
                                    response = sunlight.apicall('legislators.get', {"bioguide_id": userInfo[title]})
                                    if response is not None:
                                        if response.has_key("legislator"):
                                            #check to see if they have an official RSS, Twitter, or YouTube page

                                            legislators["digitalindex"][0].append([userInfo[title], const.FRIENDLY_NAME[userInfo[title]]])
                                            counter = 1
                                            for key in digital_key:
                                                if key == "email":
                                                    if response["legislator"].has_key("email"):
                                                        if response["legislator"]["email"] is not None:
                                                            if response["legislator"]["email"].find("@") > 0:
                                                                legislators["digitalindex"][counter].append("accept")
                                                            else:
                                                                legislators["digitalindex"][counter].append("delete")
                                                        else:
                                                            legislators["digitalindex"][counter].append("delete")
                                                    else:
                                                        legislators["digitalindex"][counter].append("delete")
                                                    
                                                else:
                                                    if response["legislator"].has_key(key):
                                                        if response["legislator"][key] is not None:
                                                            if len(response["legislator"][key]):
                                                                legislators["flags"][key].append(userInfo[title])
                                                                legislators["digitalindex"][counter].append("accept")
                                                            else:
                                                                legislators["digitalindex"][counter].append("delete")
                                                        else:
                                                            legislators["digitalindex"][counter].append("delete")
                                                    else:
                                                        legislators["digitalindex"][counter].append("delete")
                                                counter = counter + 1                         
                                            
                                            response["legislator"]["friendly_name"] = const.FRIENDLY_NAME[userInfo[title]]
                                            if const.DIGITALINDEX.has_key(userInfo[title]):
                                                response["legislator"]["digital_index"] = const.DIGITALINDEX[userInfo[title]]["digitalindex"]
                                            else:
                                                response["legislator"]["digital_index"] = 0
                                                
                                            if response["legislator"]["digital_index"] == 0:
                                                legislators["digitalindex"][counter].append("None")
                                            elif response["legislator"]["digital_index"] < 40:
                                                legislators["digitalindex"][counter].append("Low")
                                            else:
                                                legislators["digitalindex"][counter].append("Good")           
                                            legislators["legislators"].append( response["legislator"] )


                    friends_in_area = Set()
                    friends_with_app_ids = self.facebookapi.friends.getAppUsers()
                    
                    results = []
                    if friends_with_app_ids is not None:
                        if len(friends_with_app_ids) > 0:
                            for friend in friends_with_app_ids:
                                query = UserDistrict.all()
                                query.filter("uid =", int(friend))
                                results = query.fetch(1)
                                for result in results:
                                    if result.rep:
                                        if userInfo.has_key("rep"):
                                            if userInfo["rep"] == result.rep:
                                                friends_in_area.add(result.uid)
                                    if result.jrsen:
                                        if userInfo.has_key("jrsen"):
                                            if userInfo["jrsen"] == result.jrsen:
                                                friends_in_area.add(result.uid)
                                    if result.srsen:
                                        if userInfo.has_key("srsen"):
                                            if userInfo["srsen"] == result.srsen:
                                                friends_in_area.add(result.uid)          
                
                    friendList = self.facebookapi.users.getInfo(list(friends_in_area), ['uid', 'name']) 
                    legislators["friends"] = friendList
                
                           
                path = os.path.join(os.path.dirname(__file__), '../templates/transparency.fbml')
                self.response.out.write(template.render(path, legislators ))
                  
                
        except urlfetch.DownloadError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Google AppEngine ain't working"}))
            
        except facebook.FacebookError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Facebook ain't working - " + str(e.msg)})) 
            
            
        
        
            
  
def main():
	application = webapp.WSGIApplication([('/fb/transparency', MainHandler)],
									   debug=True)
	run_wsgi_app(application)

# load our custom filters		   
webapp.template.register_template_library('customfilters')

if __name__ == '__main__':
	main()
